package com.hiecho.entity;

import lombok.Builder;
import lombok.Data;

import java.util.Set;

public class CustomizeClassLoad extends ClassLoader {
    private ClassBean classBean;

    public CustomizeClassLoad(ClassBean classBean) {
        this.classBean = classBean;
    }

    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
        synchronized (getClassLoadingLock(name)) {
            // First, check if the class has already been loaded
            Class<?> c = findLoadedClass(name);
            if (c == null) {
                long t0 = System.nanoTime();
                try {
                    if (classBean.classNames.contains(name)) {
                        c = this.getParent().loadClass(name);
                    } else {
                        c = findClass(name);
                    }
                } catch (ClassNotFoundException e) {
                    // ClassNotFoundException thrown if class not found
                    // from the non-null parent class loader
                }

                if (c == null) {
                    // If still not found, then invoke findClass in order
                    // to find the class.
                    long t1 = System.nanoTime();

                    // this is the defining class loader; record the stats
                    sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0);
                    sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);
                    sun.misc.PerfCounter.getFindClasses().increment();
                }
            }

            return c;
        }
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        return super.findClass(name);
    }

    @Data
    @Builder
    public static class ClassBean {
        private String classPath;
        private Set<String> classNames;
    }
}
